import { link } from 'fs';
import { PageModalService } from './../../../shared/service/page-modal-service';
import { FormControl, FormGroup } from '@angular/forms';
import { Component, OnInit, Input } from '@angular/core';

import { AlertController, ModalController } from '@ionic/angular';

import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';

import { HttpService } from 'src/app/shared/service/http.service';
import { EventService } from 'src/app/shared/service/event.service';
import { ShareService } from 'src/app/shared/service/share.service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';

import { RemarksContentComponent } from '../../remarks-content/remarks-content.component';
import { SharePageComponent } from '../../share-page/share-page.component';
import { ProcessLoginDataService } from 'src/app/shared/service/process-login-data.service';
import { MapBaiduService } from 'src/app/shared/service/map.baiduapi';

@Component({
  selector: 'app-common-submit-btn',
  templateUrl: './common-submit-btn.component.html',
  styleUrls: ['./common-submit-btn.component.scss'],
})
// tslint:disable
export class CommonSubmitBtnComponent implements OnInit {
  @Input() tagData: any;
  keys: any;
  cssStyle: any = {};
  keyboardShow: any; // 键盘呼出
  iconBtns: any = [];
  normalBtns: any = [];
  shareData: any; // 分享页面数据
  checkMsg = '请选择分享对象';
  checked: any = [];
  isShowPriceBtn = false;
  outerBoxCssStyle: any;
  outerBoxId: any;
  closeTime: any = 0; // 计时
  timer: any;
  constructor(
    private appGlobalService: AppGlobalService,
    private http: HttpService,
    public alertController: AlertController,
    public eventService: EventService,
    public shareService: ShareService,
    public modalController: ModalController,
    public plDataService: ProcessLoginDataService,
    public mapBaiduService: MapBaiduService,
    public pageModalService: PageModalService,
  ) {
  }
  ngOnInit() {

    if (this.tagData && this.tagData.layout === 'footer') {
      window.addEventListener('keyboardWillShow', () => {
        this.keyboardShow = true;
      });
      window.addEventListener('keyboardDidHide', () => {
        this.keyboardShow = false;
      });
    }

    if (this.tagData && this.tagData.data) {

      // 2.0新增样式
      if (this.tagData.data[0] && this.tagData.data[0].outerBoxCssStyle) {
        this.outerBoxCssStyle = this.tagData.data[0].outerBoxCssStyle;
      }


      if (this.tagData.data[0] && this.tagData.data[0].outerBoxId) {
        this.outerBoxId = this.tagData.data[0].outerBoxId;
      }

      if (this.tagData.data[1] && this.tagData.data[1].closeTips) {
        let intervalId;
        if (this.tagData.data[1].closeTime) {
          this.tagData.data[1].closeTime = this.tagData.data[1].closeTime + 's';
          intervalId = setInterval(() => {
            this.tagData.data[1].closeTime.replace(/[^\d]/g, '') > 1
              ? this.tagData.data[1].closeTime = (this.tagData.data[1].closeTime.replace(/[^\d]/g, '') - 1) + 's'
              : this.tagData.data[1].closeTime = '';
            this.closeTime += 1;
          }, 1000); // 1秒加一次
        } else {
          intervalId = setInterval(() => {
            this.closeTime += 1;
          }, 1000); // 1秒加一次
        }
        this.closeTime > 20 ? clearInterval(intervalId) : '';
      }

      this.tagData.data.forEach(element => {
        if (element.icon) {
          this.iconBtns.push(element);
        } else {
          this.normalBtns.push(element);
        }

        // 如果有 改变按钮样式标记 蜂喔赚钱宝 1.7.1 新增修改需求
        if (element.changeStateThenCheck !== undefined) {
          // element.isCheck = true;
          this.eventService.eventEmit.on('changeStateThenCheck', res => {
            element.isCheck = res;
          });
        }
      });


    }

    if (this.eventService.eventEmit.listenerCount('MsCodeSubmit') > 0) {
      this.eventService.eventEmit.removeListener('MsCodeSubmit');
    }
    this.eventService.eventEmit.on('MsCodeSubmit', res => {

      const item = JSON.parse(res);
      this.submitData(item);
    });
    if (this.eventService.eventEmit.listenerCount('changeBtnTitle') > 0) {
      this.eventService.eventEmit.removeListener('changeBtnTitle');
    }
    this.eventService.eventEmit.on('changeBtnTitle', res => {
      const items = JSON.parse(res);
      const count = this.normalBtns.length < items.length ? this.normalBtns.length : items.length;

      for (let index = 0; index < count; index++) {
        const element = this.normalBtns[index];
        element.label = items[index];
      }

    });
    // 选择指定对象分享
    if (this.eventService.eventEmit.listenerCount('recommendShareCheckList') > 0) {
      this.eventService.eventEmit.removeListener('recommendShareCheckList');
    }
    this.eventService.eventEmit.on('recommendShareCheckList', res => {
      this.appGlobalService.tmpParams = res['nextPageParam'];
    });
    if (this.eventService.eventEmit.listenerCount('alreadyRecommendAllResult') > 0) {
      this.eventService.eventEmit.removeListener('alreadyRecommendAllResult');
    }
    this.eventService.eventEmit.on('alreadyRecommendAllResult', res => {
      this.checked = res;
    });

    // this.appGlobalService.priceBtns = undefined;

    // 1.9.19 蜂喔用户 找阿姨 -》 家电清洗-》立即下单
    if (this.normalBtns && this.normalBtns.length > 0) {
      if (this.normalBtns[0].action !== undefined && this.normalBtns[0].action === 'price') {
        this.isShowPriceBtn = true;
        this.appGlobalService.priceBtns = this.normalBtns;
      }
    }

  }
  valid(formGroup: FormGroup, allLabel, compareArray, callback: Function) {
    if (formGroup.valid) {
      const params = formGroup.value;
      const formKeyObj: any = {};

      for (const prop in params) {
        if (Array.isArray(params[prop])) {
          params[prop] = params[prop].join(',');
        }
        if (prop === '') {
          // delete params[prop];
        }
        if (prop.indexOf('samekey_') > -1) {
          const p = prop.replace('samekey_', '');
          params[p] = params[prop] ? params[prop] : "";
          delete params[prop];
        }
        if (prop.indexOf('cus_') > -1) {
          const p = prop.substring(4, prop.length - 1);
          formKeyObj[p] = formKeyObj[p] ? formKeyObj[p] : [];
          formKeyObj[p].push(params[prop]);
          formGroup.removeControl(prop);
          delete params[prop];
        }
      }
      // 组合表单值
      for (const key in formKeyObj) {
        if (Array.isArray(formKeyObj[key])) {
          const value = formKeyObj[key].join(',');
          formGroup.patchValue({ [key]: value });
        }
      }
      let compare = true;
      for (let index = 0; index < compareArray.length; index++) {
        const compareItem = compareArray[index];
        // 处理图片/视频--图片最小数限制
        if (compareItem.formType && compareItem.formType === 'photo') {
          const valueStr = params[compareItem.minKey];
          const valueArray = valueStr.split(';')
          if (valueArray.length < compareItem.minSize) {
            compare = false;
            if (compareItem.lessTip && compareItem.lessTip.length > 0) {
              this.appGlobalService.showToast(compareItem.lessTip, 2000, 'top');
            } else {
              this.appGlobalService.showToast(`${compareItem.label}数量最小为${compareItem.minSize}`, 3000, 'top');
            }
          }
        } else if (Number(params[compareItem.minKey]) > Number(params[compareItem.maxKey])) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.lessTip && compareItem.lessTip.length > 0) {
            this.appGlobalService.showToast(compareItem.lessTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }
          compare = false;

        } else if (Number(params[compareItem.minKey]) === Number(params[compareItem.maxKey]) && Number(params[compareItem.minKey]) != 0) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.canEqual) {

          } else if (compareItem.equalTip && compareItem.equalTip.length > 0) {
            this.appGlobalService.showToast(compareItem.equalTip, 3000, 'top');
            compare = false;
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
            compare = false;
          }


        }
      }
      if (compare) {
        callback(params);
      }
    } else {
      this.getErrors(formGroup, allLabel);
    }
  }

  getErrors(form, allLabel) {
    const errs = [];
    for (const name in form.controls) {
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }
    if (errs.length) {
      const errItem = errs[0];
      const firstErrMsgKey = Object.keys(errItem.err)[0];
      console.log(errItem.key, '校验的字段名:value' + form.value[errItem.key]);
      const messageObj = allLabel[errItem.key];
      const showMessage = messageObj[firstErrMsgKey];
      this.appGlobalService.showToast(showMessage, 500, 'top');
    }
  }
  async check(item) {

    // 蜂喔商户1.6.17 按钮检测是否有 changeStateThenCheck
    if (item.changeStateThenCheck !== undefined && item.changeStateThenCheck === 'true' && item.isCheck === undefined) {
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
      return;
    }

    if (item.isCheck !== undefined && item.isCheck === false) {
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
      return;
    }
    if (this.appGlobalService.tmpParams !== undefined) {
      // 1.9.0 蜂喔维保新增替换选中的商机id需求
      if (item.link && item.link.params && item.link.params.checkSelect !== undefined) {
        const obj = Object.assign(item.link.params, this.appGlobalService.tmpParams);
        item.link.params = obj;
      }
    }
    else {
      if (item.link && item.link.params && item.link.params.checkSelect !== undefined) {
        if (item.link.params.checkSelectMsg !== undefined) {
          this.checkMsg = item.link.params.checkSelectMsg;
        }
        this.appGlobalService.showToast(this.checkMsg, 1500, 'middle');
        return;
      }
    }

    if (item.disabled === true || item.disabled === 'true') {
      return;
    }
    if (item.action === 'saveDraft') {
      this.appGlobalService.saveFormData(1);
    } else if (item.action === 'close') {
      this.closeModal();
      this.appGlobalService.popTarget();
      history.go(-1);
    } else if (item.action === 'closeNoBack') {
      if (this.closeTime > 0) {
        this.closeModal(item);
      } else {
        this.closeModal();
      }
    }
    else if (item.action === 'reset') {
      this.closeModal();
      item.disabled = true;
      const keyString: string = item.paramName;
      this.keys = keyString.split(',');
      this.keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);
        if (formGroup) {
          formGroup.reset();
        }
      });
      item.disabled = false;
    } else if (item.action === 'submit') {
      if (item.label === '发送邀约') {
        this.sendInvitationMsg(item);
      } else {
        this.submitAction(item);
      }
    } else if (item.action === 'submitShare') {
      this.submitAction(item);
    } else if (item.action === 'submitForm') {
      this.presentModal(item); // 弹窗 表单
    } else if (item.action === 'share') {
      this.share(item.link, {}); // 分享
    } else if (item.action === 'link') {

      // 蜂喔赚钱宝1.7.1 新增 footerBtn用于清空footer控件
      if (this.appGlobalService.footerButton !== undefined) {
        this.appGlobalService.footerButton = undefined;
        localStorage.setItem('needRefresh', 'true');
      }
      
      if (item.needRefresh && item.needRefresh === 'true') {
        localStorage.setItem('needRefresh', 'true');
      }

      this.closeModal();
      item.disabled = false;
      this.pageModalService.openPage(item.link);
    } else if (item.action === 'question') {
      this.question(item);
    } else if (item.action === 'password') {
      this.question(item);
    } else if (item.action === 'questionCall') {
      this.closeModal();
      this.call(item);
    } else if (item.action === 'actionSheet') {
      this.closeModal();
      this.showAction(item);
    } else if (item.action === 'closeModal') {
      this.closeModal(item);
      this.checkEmitForRefreshData(null, item); // 2024.03.19 
      if (item.back) {
        const back = Math.abs(Number(item.back));
        for (let index = 0; index < back; index++) {
          this.appGlobalService.popTarget();
        }
        this.eventService.eventEmit.emit("loadFooterComponent", []);
        this.appGlobalService.goBack(Number(item.back));
        if (item.needRefresh === "true") {
          this.http.reloadCurrentPage();
          setTimeout(() => {
            localStorage.setItem('needRefresh', 'true');
          }, 1000);
        }
      } else if (item.onlyBack) {
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      }
    } else if (item.action === 'pageModal') {
      if (item.link) {
        this.pageModalService.openPage(item.link, '', result => {
          if (result) {
          }
        });
      }
    } else if (item.action === 'chat') {
      this.pageModalService.openPage(item.link, '', result => {
        if (result) { }
      });
    } else if (item.action === 'openApp') {
      if (item.submit) {
        this.submitAction(item);
      } else {
        if (item.customeType !== undefined) {
          this.pageModalService.openApp(item.customeType);
        } else {
          this.pageModalService.openApp();
        }
      }

    } else if (item.action === 'qrCode') {
      localStorage.setItem('qrCodeRequestCode', '1');
      this.eventService.eventEmit.emit('qrCode', 'qrCode');
    } else if (item.action === 'callRightNow') {
      this.http.changeCallNumber(item.phone);
    } else if (item.action === 'copy') {
      this.shareService.copyUrl(item.copyText);
    } else if (item.action === 'setDefValue') {
      this.eventService.eventEmit.emit('setDefValue', JSON.stringify(item));
    } else if (item.action === "back") {
      if (item.back) {
        const back = Math.abs(Number(item.back));
        for (let index = 0; index < back; index++) {
          this.appGlobalService.popTarget();
        }
        this.eventService.eventEmit.emit("loadFooterComponent", []);
        this.appGlobalService.goBack(Number(item.back))
        if (item.needRefresh === "true") {
          // 2024.10.29 
          this.http.reloadCurrentPage(item.updateTime); 
          setTimeout(() => {
            localStorage.setItem('needRefresh', 'true');
          }, 1000);
        }
      } else {
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      }
    } else if (item.action === "emitFilterTime") {
      this.eventService.eventEmit.emit("emitFilterTime", item.submit);
    } else if (item.action === "emitcertificateList") {
      this.eventService.eventEmit.emit("emitcertificateList", item);
    } else if (item.action === "emitWriteOffList") {
      this.eventService.eventEmit.emit("emitWriteOffList", item);
    } else if (item.action === "downloadImage") {
      this.appGlobalService.saveImageFromUrl(item.imgUrl, 'img' + new Date().getTime());

    } else if (item.action === "relocation") {
      this.http.delayShowLoading();
      // 2023年8月25日新增重新定位
      this.mapBaiduService.onlyRefreshCurrentPositionAndCallBack(() => {
        // this.eventService.emit("getLocationDone", "true");
        localStorage.removeItem('mapPosition');
        const targetObj = JSON.parse(localStorage.getItem('targetObj'));
        const position = JSON.parse(localStorage.getItem('position'))
        if (targetObj && targetObj.bat && targetObj.bat.length > 0) {
          targetObj.forward = targetObj.bat[targetObj.bat.length - 1];
          if (targetObj.forward && targetObj.forward.params && targetObj.forward.params.location) {
            targetObj.forward.params.location = null;
            delete targetObj.forward.params.location;
          }
          targetObj.forward.params.longitude = position.center.lng;
          targetObj.forward.params.latitude = position.center.lat;
          localStorage.setItem('targetObj', JSON.stringify(targetObj));
        }
        this.appGlobalService.reloadCurrentPage();
      });
    }
  }
  async call(item) {
    const alert = await this.alertController.create({
      header: this.tagData.data.nick_name,
      message: item.question,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary'
        }, {
          text: '拨打',
          handler: () => {
            this.http.changeCallNumber(item.phone);
          }
        }
      ]
    });
    await alert.present();
  }
  sendInvitationMsg(item) {
    if (item.submit) {
      item.submit.sessionId = localStorage.getItem('sessionId');
      this.http.post('application/submit', item.submit, res => {
        if (res.success) {
          this.sendInvitationMsgItem(item);
        } else {
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
      });
    } else {
      this.sendInvitationMsgItem(item);
    }
  }
  sendInvitationMsgItem(item) {
    if (localStorage.getItem('userId') !== 'null') {
      const positionInfo = JSON.parse(localStorage.getItem('position'));
      if (localStorage.getItem('invitationArr')) {
        const arr = JSON.parse(localStorage.getItem('invitationArr'));
        const len = arr.length;
        if (item.link.params.customer_id) {
          this.http.getImId(undefined, item.link.params.customer_id, positionInfo.code ? positionInfo.code : 4403, (resItem) => {
            if (document.getElementById('invitation_remark_msg')) {
              const remark = document.getElementById('invitation_remark_msg')['value'];
              if (String(remark).trim().length > 0) {
                localStorage.setItem('onSendWebSocketMessageTag', 'true');
                const nowDate = Date.now();
                this.eventService.eventEmit.emit("onSendWebSocketMessage", { text: String(remark).trim(), toId: resItem.toId, fromId: localStorage.getItem('connUserId'), key: resItem.id, type: 'general', nowDate });
              }
            }
            if (arr[0]) {
              let conent = '';
              if (arr[0].message) {
                conent = arr[0].message;
              }
              localStorage.setItem('onSendWebSocketMessageTag', 'true');
              const nowDate = Date.now();
              this.eventService.eventEmit.emit("onSendWebSocketMessage", { text: conent, toId: resItem.toId, fromId: localStorage.getItem('connUserId'), key: resItem.id, type: 'general', nowDate });
            }
            for (let i = 0; i < len; i++) {
              ((i) => {
                setTimeout(() => {
                  const oppDetail = arr[i];
                  localStorage.setItem('onSendWebSocketMessageTag', 'true');
                  const nowDate = Date.now();
                  const message = {
                    text: oppDetail.title,
                    toId: resItem.toId,
                    fromId: localStorage.getItem("connUserId"),
                    key: resItem.id,
                    type: 'opp',
                    rentunit: resItem.rentunit ? resItem.rentunit : '元/月',
                    opportunity_id: oppDetail.id,
                    title: oppDetail.title,
                    imags: oppDetail.imageUrl ? oppDetail.imageUrl : undefined,
                    pluginId: oppDetail.plugin,
                    big_district: oppDetail.big_district ? oppDetail.big_district : '',
                    district: oppDetail.district ? oppDetail.district : '',
                    area: oppDetail.area ? oppDetail.area : '',
                    industry: oppDetail.industry ? oppDetail.industry : '',
                    rent: oppDetail.rent ? oppDetail.rent : '',
                    transfer_fee: oppDetail.transfer_fee ? oppDetail.transfer_fee : '',
                    nowDate
                  };
                  this.eventService.eventEmit.emit("onSendWebSocketMessage", message);
                }, (i + 1) * 50);
              })(i);
            }
            setTimeout(() => {
              item.disabled = false;
              if (item.back) {
                this.appGlobalService.goBack(Number(item.back));
                if (Number(item.back) < 0) {
                  const back = Math.abs(Number(item.back));
                  for (let index = 0; index < back; index++) {
                    this.appGlobalService.popTarget();
                  }
                }
                localStorage.setItem("needRefresh", "true");
                this.appGlobalService.showToast('发送邀约成功', 2000, 'middle');
              }
            }, 0);
          });
        }
      }
    }
  }
  submitAction(item) {
    item.disabled = true;
    const keyString: string = item.paramName;
    this.keys = keyString.split(',');
    let count = 0;
    let formCount = 0;
    let nextPageOK = true;
    try {
      this.keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);
        const messageObj = this.appGlobalService.getFormGroupMessageWithParamName(element);
        const compareArray = this.appGlobalService.getFormCompareWithParamName(element);
        // 确保是一个有效的表单
        if (this.appGlobalService.globalHiddenForm && messageObj) {

          if (this.appGlobalService.globalHiddenForm.valid) {
            for (const cons in this.appGlobalService.globalHiddenForm.controls) {

              if (formGroup.contains(cons)) {
                formGroup.patchValue({ [cons]: this.appGlobalService.globalHiddenForm.controls[cons].value });
              } else {
                formGroup.addControl(cons, new FormControl(this.appGlobalService.globalHiddenForm.controls[cons].value));
              }

            }
          } else {

            this.getErrors(this.appGlobalService.globalHiddenForm, this.appGlobalService.globalHiddenMessageObj);
            nextPageOK = false;
            throw new Error("error");
          }


        }

        if (formGroup && messageObj) {
          formCount += 1;
          this.appGlobalService.formChecked = true;
          this.valid(formGroup, messageObj, compareArray, params => {
            if (params) {
              if (params['locationAddressLabel']) {
                item['locationAddressLabel'] = params['locationAddressLabel'];
              }
              if (item.submit.content && item.submit.content.passwordKey) {
                const enkeys = item.submit.content.passwordKey.split(',');
                enkeys.forEach(enkey => {
                  if (params[enkey])
                    params[enkey] = this.appGlobalService.encryptDes(params[enkey]);

                });
              }
              item.submit.content[element] = params;
              count += 1;
              if (item.submit.content && item.submit.content.wraps) {
                // wraps 用于取指定key的value检测敏感词 "wraps"："key1#formkey1,key2#formkey2"
                const wraps = item.submit.content.wraps;
                const keys = wraps.split(',');
                keys.forEach(key => {
                  const k = key.split('#')
                  if (params[k[1]]) {
                    item.submit.content[k[0]] = params[k[1]];
                  }
                });

              }
            } else {
              item.disabled = false;
              return;
            }
          });
        } else {
          if (localStorage.getItem(element)) {
            const obj = JSON.parse(localStorage.getItem(element));
            // 加了参数在下层
            if (obj.data && obj.data.length) {
              obj.data.forEach(e => {
                obj[e.formKey] = e.value;
              });
              // 包含人工价格
              if (Number(obj.totalPrice) > 0) {
                obj.price = obj.totalPrice;
              }
              delete obj.data;
              delete obj.contentList;
              item.submit.content[element] = obj;
            } else {
              item.submit.content[element] = obj;
            }

          }
        }
      });

    } catch (error) {
      if (error.message != "error") throw error;

    }

    // 全部校验通过
    if (count === formCount && nextPageOK) {
      // 提现密码输入
      if (item.needPassword) {
        this.pageModalService.openPasswordModal('', res => {
          if (res && res.length === 6) {
            // console.log('pw:' + res);
            if (item.submit.content && item.submit.content.passwordKey) {
              item.submit.content[item.submit.content.passwordKey] = this.appGlobalService.encryptDes(res);
            }
            this.submitData(item)
          } else {
            item.disabled = false;
          }
        })

      } else if (item.submit.content && item.submit.content.needMsCode && item.submit.content.phoneKey && item.submit.content.msCodeKey) {
        // 发布短信验证码
        // <param name="needMsCode" value="true"/><!--1 验证码弹窗 不可以跳过，2 可以跳过 3 比较登录号码 不可以跳过，号码相同不弹窗-->
        // <param name="phoneKey" value="company_phone"/><!--phoneKey 指向电话号码的key-->
        // <param name="msCodeKey" value="msCode"/><!--msCodeKey 指向验证码的key，比如msCode=2828-->

        // 3 比较登录号码 不可以跳过，号码相同不弹窗
        if (localStorage.getItem('loginAccount') == item.submit.content[item.submit.content.phoneKey] && localStorage.getItem('loginStatus') === 'true' && item.submit.content.needMsCode === '3') {
          this.submitData(item)
        } else {
          this.pageModalService.openMsCodeModal(item, res => {
            if (res && res === 0) {
              // 跳过
              this.submitData(item)
            } else {
              item.disabled = false;
            }
          })
        }

      } else {
        this.submitData(item)
      }

    } else {
      item.disabled = false;
    }
  }

  // 2024.03.19
  checkEmitForRefreshData(res, item) {
    if (item.commentsListTag !== undefined) {
      if (res !== null && res.data !== undefined) {
        const singleDataName = item.commentsListTag + '_singleData';
        this.eventService.eventEmit.emit(singleDataName,
          {
            key: item.key,
            keyValue: item.keyValue,
            viewId: item.viewId,
            value: item.submit.content[item.key],
            updateItemType: item.updateItemType,
            pluginId: item.pluginId,
            result: res.data.eventResult
          });
      } else if (res === null) {
        const singleDataName = item.commentsListTag + '_singleData';
        this.eventService.eventEmit.emit(singleDataName,
          {
            key: item.key,
            keyValue: item.keyValue,
            viewId: item.viewId,
            updateType: item.updateType,
            updateItemType: item.updateItemType,
            pluginId: item.pluginId,
            value: item[item.key],
            result: ''
          });
      }
      const modal = this.modalController.getTop();
      if (modal && modal['__zone_symbol__value'] !== undefined) {
        this.modalController.dismiss();
      }
    }
  }



  submitData(item) {
    // page 获取 表单值为参数 直接走page
    if (item.link && item.link.type === 'pageModal' && item.link.params && item.link.params.stopSubmit === 'true') {

      item.disabled = false;
      const keyString: string = item.paramName;
      this.keys = keyString.split(',');
      this.keys.forEach(element => {
        if (localStorage.getItem(element)) {
          Object.assign(item.link.params, item.submit.content[element]);
        }
      });

      this.pageModalService.openPage(item.link);

      return;
    }

    item.submit.sessionId = localStorage.getItem('sessionId');

    // 蜂喔赚钱宝1.7.1 已推荐信息选中取消推荐传ID
    if (this.checked !== undefined && this.checked.length > 0) {
      if (item.submit && item.submit.content && item.submit.content[item.paramName]) {
        // id数组传参
        item.submit.content[item.paramName] = JSON.stringify(this.checked);
      } else if (item.submit && item.submit.content && item.submit.content.idKey) {
        item.submit.content[item.submit.content.idKey] = this.checked.join(',');
      }
    }

    // 1.7.1 最新蜂喔服务店改动需求 指定分享对象 带事件参数参数
    if (item.submit && item.submit.content && item.submit.content.eventParamsWithSubmit !== undefined) {
      const obj = Object.assign(item.submit.content, this.appGlobalService.tmpParams);
      item.submit.content = obj;
    }
    this.http.delayShowLoading()
    this.http.post('application/submit', item.submit, async res => {
      if (res.success) {

        // 2.2.16 蜂喔用户弹窗选择默认地址
        if (item.submit
          && item.submit.content
          && item.submit.content.needStorePosition
          && item.submit.content.needStorePosition === 'true') {
          const results = res.data.eventResult.split(',');
          if (results.length > 0 && res.data.eventResult.indexOf('.') > -1) {
            this.appGlobalService.getAddressLat = results[0];
            this.appGlobalService.getAddressLng = results[1];
          }
          this.appGlobalService.addressEventResultValue = res.data.eventResult;
        }
        this.checkEmitForRefreshData(res, item);
        this.appGlobalService.nextPageFomObj = undefined;
        if (item.delItem !== undefined) {
          this.eventService.eventEmit.emit('delItemCommentsList', 1);
        }
        try {
          if (item.submit && item.submit.content && item.submit.content.NoShowSubmit) {
            // 表单中一下步的弹窗id
            setTimeout(async () => {
              this.modalController.dismiss({}, '', 'NoShowSubmit');

            }, 0);

          }

        } catch (error) {

        }
        //  优化多个弹窗关闭的判断顺序 
        try {
          if (item.submit && item.submit.content && item.submit.content.closeAllModal) {
            this.pageModalService.closeAllModal();
            this.success(res, item);
          } else if (item.skipCloseAllModal === undefined && this.pageModalService.modalIdArray && this.pageModalService.modalIdArray.length > 1) {
            this.pageModalService.closeAllModal();
            this.success(res, item);
          } else {
            if (this.appGlobalService.globalSubmitBtnData) {

              this.modalController.dismiss();
              setTimeout(() => {
                this.success(res, item);
              }, 200);
            } else {
              const modal = await this.modalController.getTop();
              if (modal) {
                this.modalController.dismiss({ data: true });
              }
              this.success(res, item);
            }
          }
        } catch (error) { }

        this.appGlobalService.globalSubmitBtnData = null;
        this.appGlobalService.globalHiddenForm = null;
      } else {
        // 发布 验证码验证失败 弹窗不消失
        if (item.submit.content && item.submit.content.needMsCode && item.submit.content.phoneKey && item.submit.content.msCodeKey && item.submit.content[item.submit.content.msCodeKey] && item.submit.content[item.submit.content.msCodeKey].length == 6) {

          if (res.message && res.message.length > 0) {
            this.appGlobalService.showToast(res.message, 2000, 'middle');
          }
          return;
        }



        // setTimeout(async () => {
        //   this.modalController.dismiss({}, '', 'NoShowSubmit');
        // }, 0);
        const modal = await this.modalController.getTop();
        if (modal) {
          modal.dismiss('success');
        }

        // 2.0 新增一种处理 处理关闭modal
        if (res.params && res.params.needRefresh !== undefined) {
          if (res && res.params && res.params.refresh) {
            if (Number(res.params.refresh) > 0) {
              this.http.reloadCurrentPage();
              // localStorage.setItem("needRefresh", "true");
              return;
            }
          }
        }

        // 提现
        if (item.submit.content && item.submit.content.passwordKey) {
          //1005是重试
          // 1006是超过次数
          if (res.code === 1005) {
            this.retry(item, res);
          } else if (res.code === 1006) {
            this.retry(item, res);
          } else {
            if (res.message && res.message.length > 0) {
              this.appGlobalService.showToast(res.message, 2000, 'middle');
            }
          }

        } else {
          if (res.message && res.message.length > 0) {
            this.appGlobalService.showToast(res.message, 2000, 'middle');
          }
        }

      }
      setTimeout(() => {
        item.disabled = false;
      }, 500);

    }, error => {
      item.disabled = false;
    });
  }


  async retry(item, res) {
    const that = this;
    const alert = await this.alertController.create({
      header: '',
      subHeader: '',
      message: res.message ? res.message : '提现密码错误',
      buttons: [{
        text: '忘记密码',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('忘记密码');
          // link
          item.disabled = false;
          this.pageModalService.openPage(item.link);

        }
      }, {
        text: res.code === 1005 ? '重试' : '好的',
        cssClass: 'LJ',
        handler: () => {
          console.log('res.code：' + res.code);
          item.submit.content[item.submit.content.passwordKey] = '';
          // const keyString: string = item.paramName;
          // this.keys = keyString.split(',');
          // this.keys.forEach(element => {
          //   const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);
          //   if (formGroup) {
          //     formGroup.reset();
          //   }
          // });
        }
      }]
    });
    await alert.present();
  }

  async question(item) {
    const that = this;
    const alert = await this.alertController.create({
      header: '',
      subHeader: '',
      message: item.question,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          if (item.submit) {
            that.submitAction(item);
          } else if (item.link) {
            item.disabled = false;
            this.pageModalService.openPage(item.link);
          }
        }
      }]
    });
    await alert.present();
  }
  async presentModal(item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'remarks',
      component: RemarksContentComponent,
      componentProps: { item, type: 'submitForm' }
    });
    await modal.present();
    const modalData = await modal.onDidDismiss();
  }

  success(res, item) {
    this.appGlobalService.delFormData();
    if (item['locationAddressLabel']) {
      this.appGlobalService['locationAddressLabel'] = item['locationAddressLabel'];
    }
    if (item.action === 'openApp') {
      if (item.customeType !== undefined) {
        this.pageModalService.openApp(item.customeType);
      } else {
        this.pageModalService.openApp();
      }
      return
    }
    // 蜂喔商户1.6.22 新增type参数
    if (item.linkType) {
      res.type = item.linkType;
    }
    //1 表示page, 2 h5, 3 download,4 popup win 入驻分享根据结果可能是page 、modal
    if (res.skip && res.params && res.params.useSkip && res.params.useSkip === 'true' && res.target){
      if (res.skip == 1) {
        res.type = 'page';
      } else if (res.skip == 4) {
        res.type = 'modal';
      } else if (res.skip == 2) {
        res.type = 'url';
      }
      
    }
    // dismisskey 2.0 新增参数
    if (res.params && res.params.dismissKey !== undefined) {
      // 如果已经选择了小区则标记选择
      localStorage.setItem('alreadySelectArea', 'true');
    }
    if (res.params.fromAddressList !== undefined) {
      if (res.params.returnAddressIdKey) {
        setTimeout(() => {
          const addressItem = {
            id: res.params[res.params.returnAddressIdKey]
          };
          addressItem.id === undefined ? addressItem.id = res.params.returnAddressIdKey : '';
          if (res.params.fromAddressList === "1") {
            // 地址列表-> 新增/修改 后返回->列表
            this.eventService.emit("updateAddress", addressItem);
          } else {

            // 发布-> 新增 后返回->发布
            this.eventService.emit("selectAddress", addressItem);
          }
        }, 1000);

      }
    }
    if (res.params && res.params.returnInvoiceHeadIdKey !== undefined && res.params[res.params.returnInvoiceHeadIdKey] !== undefined) {
      this.appGlobalService.popTarget();
      // 获取到添加发票抬头成功的 地址id 返回不可以设置刷新上一页
      localStorage.setItem("needRefresh", "false");
      const idItem = {
        id: res.params[res.params.returnInvoiceHeadIdKey]
      };
      // 发布-> 新增 后返回->发布
      this.eventService.emit("invoice-head-id", idItem);

      this.appGlobalService.goBack();

    }

    if (item.is_favorite === 'true') {
      item.is_collection = item.is_collection === 'true' ? 'false' : 'true';
    }

    if (res.message) {
      // 2.1.0 新增参数
      if (item.submit.content && item.submit.content.showSuccesIcon) {
        this.appGlobalService.showToast(res.message, 2000, "middle", item.submit.content.showSuccesIcon);
      } else {
        this.appGlobalService.showToast(res.message, 2000, "middle");
      }
    }
    if (item.tabClick) {
      const tabIndex = parseInt(item.tabClick);
      this.eventService.eventEmit.emit("topTabChangeByIndex", tabIndex);
      //todo: localStorage.setItem('subTab_index', item['subTab_index']);
    }
    // 重置表单
    if (res && res.params && res.params.reset) {
      const keyString: string = item.paramName;
      this.keys = keyString.split(',');
      this.keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);
        if (formGroup) {
          formGroup.reset();
        }
      });
      item.disabled = false;
    }
    
    // 蜂喔赚钱宝1.7.1 新增 refresh
    if (res && res.params && res.params.refresh) {
      if (Number(res.params.refresh) > 0) {
        if (res.params.refreshAfterMilliSecond !== undefined) {
          this.http.reloadCurrentPage(Number(res.params.refreshAfterMilliSecond));
        } else {
          this.http.reloadCurrentPage();
        }
        // localStorage.setItem("needRefresh", "true");
        return;
      }
    }
    if (item.action === 'submitShare' && item.link) {
      this.share(item.link, res);
    } else if (item.back) {
      if (Number(item.back) < 0) {
        const back = Math.abs(Number(item.back));
        for (let index = 0; index < back; index++) {
          this.appGlobalService.popTarget();
        }
        this.appGlobalService.goBack(Number(item.back));
        if (item.submit.content.afterGoBackRefresh !== undefined) {
          setTimeout(() => {
            this.appGlobalService.reloadCurrentPage();
          }, 50);
          return;
        }
        if (item.submit.content.needRefresh) {
          this.needRefreshTab();
        }
        // 1.9.18 用于新增点击弹窗保存返回按钮执行刷新处理
        if (item.disableRefreshAfterBack !== undefined) {
          return;
        }
      } else if (Number(item.back) === 0) {
        this.http.reloadCurrentPage();
        // 提交成功页面刷新 并弹窗新的弹窗
        if ((res && (res.type === 'pageModal' || res.type === 'modal' || res.type === 'model')) || (item.link && (item.link.type === 'modal' || item.link.type === 'pageModal'))) {
          if (res.data && res.data.eventResult && res.params && res.params.eventResult) {
            res.params[res.params.eventResult] = res.data.eventResult;
          }
          const modalLink = {
            target: res.target,
            params: res.params ? res.params : {},
            sessionId: localStorage.getItem('sessionId')
          };
          modalLink['type'] = res.type;
          setTimeout(() => {
            this.pageModalService.openPage(modalLink, '', res => {
              // 提现
              if (item.submit.content.passwordKey) {
                this.needRefreshTab();
              }
            });
          }, 2000);

        }
      } else {
        this.appGlobalService.goBack(Number(item.back));
      }
      // localStorage.setItem("needRefresh", "true");
    }
    else if (res.target && res.type === 'updateItem') {
      const link = {
        pageId: res.target,
        params: res.params ? res.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      this.modalController.dismiss({ data: link });

    } else if ((res && (res.type === 'modal' || res.type === 'model')) || (item.link && (item.link.type === 'modal' || item.link.type === 'pageModal'))) {
      if (res.data && res.data.eventResult && res.params && res.params.eventResult) {
        res.params[res.params.eventResult] = res.data.eventResult;
      }
      const modalLink = {
        target: res.target,
        params: res.params ? res.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      modalLink['type'] = res.type;
      this.pageModalService.openPage(modalLink, '', res => {
        // 提现
        if (item.submit.content.passwordKey) {
          this.needRefreshTab();
        }
      });
    }

    else if (item.link && item.link.type === 'page') {
      if (res.data && res.data.eventResult && item.link.params && item.link.params.eventResult) {
        if (res.data.eventResult) {
          item.link.params[item.link.params.eventResult] = res.data.eventResult;
        } else {
          item.link.params[item.link.params.eventResult] = res.eventResult;
        }
      }
      this.pageModalService.openPage(item.link);
    } else if (res.target) {
      if (res.data && res.data.eventResult && res.params && res.params.eventResult) {
        res.params[res.params.eventResult] = res.data.eventResult;
      }
      const link = {
        target: res.target,
        params: res.params ? res.params : {}, type: res.type
      }
      if (res.params.enableLink !== undefined && res.params.enableLink === 'false') {
        return;
      }
      this.pageModalService.openPage(link);
    }
  }
  showAction(item) {
    if (item.listItems && item.listItems.length > 0) {
      const that = this;
      const buttons: any = [];
      item.listItems.forEach((element, index) => {
        buttons.push(element.label);
      });
      ActionSheetService.showActionSheetWithOptions(
        {
          options: buttons,
          maskClosable: true
        },
        buttonIndex => {
          if (buttonIndex > -1) {
            ActionSheetService.close();
            setTimeout(() => {
              that.selectItem(item, buttonIndex);
            }, 200);
          }
        }
      );
    }
  }
  selectItem(itemObj, index) {
    if (itemObj.modelType === 'iconSubmit') {
      let submit;
      if (itemObj.button && itemObj.button.submit) {
        submit = itemObj.button.submit;
      } else if (itemObj.submit) {
        submit = itemObj.submit;
      }
      // 支持submit
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.http.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.refresh !== undefined) {
            this.appGlobalService.reloadCurrentPage();
          }
          this.pageModalService.openPage(itemObj.listItems[index].link);
        }
      });
    } else if (itemObj.listItems[index].submit) {
      let submit = itemObj.listItems[index].submit;
      // 支持submit
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.http.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.refresh !== undefined) {
            this.appGlobalService.reloadCurrentPage();
          }
          this.pageModalService.openPage(itemObj.listItems[index].link);
        }
      });
    } else {
      this.pageModalService.openPage(itemObj.listItems[index].link);
    }
  }
  demoData() {
    this.tagData = {
      type: "tag",
      style: "xxxx",
      name: "xxxx",
      layout: "footer",
      cssStyle: "padding:20px 0;text-align:center;",
      data: [
        {
          action: "link", // / submit / reset", question // 跳转，提交及重置 / sumitForm
          paramName: "linkKey", // , 隔开多个
          label: "确认购买",
          cssColor: "orange", // / brown / blue / gray / lightBule",
          plain: false, // 是否朴素按钮,默认为false
          round: true, // 是否圆形按钮,默认为false
          disabled: false, // 是否禁用状态,false为可用,默认为false
          size: "small", /// big/ small / mini", // 目前只有中等和小的尺寸，默认为中等尺寸
          htmlObj: [ // 内嵌表单 使用弹出方式展示
            {
              compare: false,
              formType: "textArea",
              showValue: "aaa",
              hidden: false,
              formKey: "transfer_reason",
              rules: [
                {
                  name: "pattern",
                  message: "请填写正确转让原因",
                  value: "^[\u4e00-\u9fa5_a-z A-Z1-9_\d_\w!#.，。；;？㎡()（）【】、$%*+/=?.^_`{}~-]{0,300}$"
                }
              ],
              label: "转让原因",
              value: "aaa",
              maxLength: 260,
              placeHolder: "选填"
            }
          ],
          submit: {
            id: "string",
            content: {
            }
          },
          link: {
            type: "page",
            target: "pageId",
            params: {}
          },
          question: "确定结束本次服务？"
        },
        // {
        //   action: "link", // / submit / reset", question // 跳转，提交及重置
        //   paramName: "linkKey", // , 隔开多个
        //   label: "确认购买",
        //   cssColor: "orange", // / brown / blue / gray / lightBule",
        //   plain: true, // 是否朴素按钮,默认为false
        //   round: false, // 是否圆形按钮,默认为false
        //   disabled: false, // 是否禁用状态,false为可用,默认为false
        //   size: "small", /// big/ small / mini", // 目前只有中等和小的尺寸，默认为大等尺寸
        //   submit: {
        //     id: "string",
        //     content: {
        //     }
        //   },
        //   link: {
        //     type: "page",  
        //     target: "pageId",
        //     params: {}
        //   },
        //   question: "确定结束本次服务？"
        // }
      ]
    };
  }

  async closeModal(value?) {
    const modal = await this.modalController.getTop();
    if (modal !== undefined) {
      if (value && value.closeTips !== undefined) {
        if (!this.timer) {
          this.timer = setTimeout(() => {
            if (value.closeTips === 'canEditForm' && (this.closeTime > 10 || !this.tagData.data[1].closeTime)) { // 大于10秒 并阅读完

              if (value.submit) {
                const params = {
                  content: value.submit.content,
                  id: value.submit.id,
                  sessionId: localStorage.getItem("sessionId")
                };
                this.http.post("application/submit", params, res => {
                  if (res.success) {
                  }
                });
              }
              modal.dismiss(value.closeTips);
            } else if (value.closeTips === 'disableEditForm') {  // 点击取消
              modal.dismiss(value.closeTips);
            } else {
              this.appGlobalService.showToast(`请认真阅读完发布协议`, 1500, 'top');
            }
            this.timer = '';
          }, 150);
        }
      } else {
        modal.dismiss('success');
      }
    }
  }
  needRefreshTab() {
    setTimeout(() => {
      const tab = localStorage.getItem('tab');
      if (tab && tab.indexOf("tab") > -1) {
        const tabIndex = tab.substring(tab.length - 1);
        console.log("needRefreshTab" + tabIndex);
        localStorage.setItem('needRefreshTab' + tabIndex, 'true');
        this.eventService.eventEmit.emit(tab, '1');
        console.log('submit eventEmit--->' + tab);
      }
    }, 500);
  }
  getInterger(value) {
    return parseInt(value, 10);
  }
  /** 分享 */
  share(link, res) {
    console.log('share --> page', link);
    let p: any = {}
    if (res && res.params) {
      p = res.params;
    }
    // 请求参数
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: link.target,
      params: p
    };
    this.http.post('application/page', params, res => {
      const tagData = JSON.parse(res.script).views[0].tags[0];
      this.shareData = tagData.data;
      if (link.params && link.params.dismiss !== undefined) {
        this.presentShareModal_Dismiss(tagData.title);
      } else {
        this.presentShareModal(tagData.title);
      }
    });
  }
  // 分享弹框
  async presentShareModal(title) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: this.shareData, title: title === null ? "" : title }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss().then(res => {
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
    });
    // 获取关闭传回的值
    console.log(modalData);
  }

  async presentShareModal_Dismiss(title) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: this.shareData, title: title === null ? "" : title }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  ngOnDestroy(): void {
    if (this.appGlobalService.priceBtns !== undefined) {
      console.log('destory priceBtn ... ');
      // this.appGlobalService.priceBtns = undefined;
    }
  }
}
